package zsy.springframework.beans.factory.chouxiang;

import zsy.springframework.beans.factory.BeansException;
import zsy.springframework.beans.factory.celue.CglibSubclassingInstantiationStrategy;
import zsy.springframework.beans.factory.config.BeanDefinition;
import zsy.springframework.beans.factory.jiekou.InstantiationStrategy;

import java.lang.reflect.Constructor;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefiniton, Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefiniton, beanName, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        addSington(beanName, bean);
        return bean;
    }

    protected Object createBeanInstance(BeanDefinition beanDefiniton, String beanName, Object[] args) {
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefiniton.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor<?> ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanDefiniton, beanName, constructorToUse, args);
    }
}
